package com.wenjie.original.service.impl;


import cn.hutool.core.util.IdUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.wenjie.original.entity.SysRole;
import com.wenjie.original.entity.SysRoleMenu;
import com.wenjie.original.entity.vo.SysRole.SysRoleUpOrAddVo;
import com.wenjie.original.flex_config.baseInterface.Cus_ServiceImp;
import com.wenjie.original.mapper.SysRoleMapper;
import com.wenjie.original.service.ISysRoleMenuService;
import com.wenjie.original.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import static com.wenjie.original.entity.table.SysRoleMenuTableDef.SYS_ROLE_MENU;

/**
 * 角色 业务层处理
 *
 * @author wenjie
 */
@Service
public class SysRoleServiceImpl extends Cus_ServiceImp<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Override
    @Transactional
    public void cusSave(SysRoleUpOrAddVo.AddVo addVo) {
        addVo.setSysRoleId(IdUtil.getSnowflakeNextId());
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Long sysMenuId : addVo.getSysMenuIds()) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setSysMenuId(sysMenuId);
            sysRoleMenu.setSysRoleId(addVo.getSysRoleId());
            sysRoleMenus.add(sysRoleMenu);
        }

        sysRoleMenuService.saveBatch(sysRoleMenus);
        this.save(addVo);
    }


    @Override
    @Transactional
    public void cusUpdate(SysRoleUpOrAddVo.UpVo upVo) {
        // 删除
        sysRoleMenuService.remove(QueryWrapper.create().where(SYS_ROLE_MENU.SYS_ROLE_ID.eq(upVo.getSysRoleId())));

        // 添加
        List<SysRoleMenu> sysRoleMenus = new ArrayList<>();
        for (Long sysMenuId : upVo.getSysMenuIds()) {
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setSysMenuId(sysMenuId);
            sysRoleMenu.setSysRoleId(upVo.getSysRoleId());
            sysRoleMenus.add(sysRoleMenu);
        }
        sysRoleMenuService.saveBatch(sysRoleMenus);
        this.updateById(upVo);
    }

    @Override
    @Transactional
    public void cueDel(Long id) {

        // 删除角色和菜单表中的 用户信息
        sysRoleMenuService.remove(QueryWrapper.create().where(SYS_ROLE_MENU.SYS_ROLE_ID.eq(id)));

        // 删除用户表中的用户信息
        this.removeById(id);
    }


}
